package com.tln.sys.menu.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javacommon.base.BaseRestSpringController;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.binding.convert.converters.ObjectToArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fins.gt.server.GridServerHandler;
import com.tln.sys.menu.model.Menu;
import com.tln.sys.menu.service.MenuService;
import com.xjj.core.modules.dao.template.DbUtilsTemplate;
import com.xjj.core.modules.orm.Page;


/*
 * 连接方式  默认已经继承了BaseRestSpringController中的实现 
 * 各种方式的区别
 * /sys/menu                => index()  
 * /sys/menu/new            => _new()  
 * /sys/menu/{id}           => show()  
 * /sys/menu/{id}/edit      => edit()  
 * /userinfo        POST    => create()  
 * /sys/menu/{id}   PUT     => update()  
 * /sys/menu/{id}   DELETE  => delete()  
 * /sys/menu        DELETE  => batchDelete() 
 */
@Controller
@RequestMapping("/sys/menu/**")
public class MenuController extends BaseRestSpringController<Menu,java.lang.Long>{

	private static final Logger logger = LoggerFactory.getLogger(MenuController.class);
	
	private Menu menu;
	
	private MenuService menuService;
	
	@Autowired
	private DbUtilsTemplate dbUtilsTemplate;
	
	private final String LIST_ACTION = "redirect:/sys/menu";
	
	private Page<Menu> page = new Page<Menu>(20);//每页5条记录
	
	List<Menu> menuList = new ArrayList<Menu>();

	public List<Menu> getMenuList() {
		return menuList;
	}

	public void setMenuList(List<Menu> menuList) {
		this.menuList = menuList;
	}

	@Autowired
	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}
	
	//默认方法
	@Override
	public String index(HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute Menu entity,Model model) {
		logger.info("index............");
		return "/sys/menu/menuList";
	}
	
	//创建表单
	@Override
	public String create(HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute Menu entity,Model model) {
		logger.info("index............");
		model.addAttribute("entity",entity);
		model.addAttribute("done", 2);
		return "/sys/menu/createMenu";
	}
	
	//保存表单
	@Override
	public String save(HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute Menu entity,Model model) {
		logger.info("save............"+entity.getMenuName());
		this.menuService.saveMenu(entity);
		model.addAttribute("done", 1);
		return "/sys/menu/createMenu";
	}
	
	/*@RequestMapping(value="/save")
	public String save(HttpServletRequest request,HttpServletResponse response) {
		System.out.println("save........5555.............");
		//System.out.println("menu  name :  "+menu.getMenuName());
		String menuName = request.getParameter("menuName");
		String icon = request.getParameter("icon");
		System.out.println("menuName：   "+menuName);
		Menu entity = new Menu();
		entity.setMenuName(menuName);
		entity.setIcon(icon);
		this.menuService.saveMenu(entity);
		return null;
	}*/
	
	//修改表单
	//@RequestMapping(value="/edit",method= RequestMethod.GET)
	@Override
    public String edit(@PathVariable Long id,Model model ) {
    	logger.info("edit...................");
    	logger.info("id..................."+id);
    	//model.addAttribute("entity",entity);
    	Menu menu = this.menuService.getMenu(id);
    	model.addAttribute("done", 2);
    	model.addAttribute("menu", menu);
        return "sys/menu/editMenu";
    }

	//更新表单
	@Override
	public String update(@PathVariable Long id,Model model,
			HttpServletRequest request,HttpServletResponse response) throws Exception{
		logger.info("update............");
		//UserInfo userInfo = new UserInfo();//(UserInfo)userInfoManager.getById(id);
		Menu menu = (Menu)menuService.getMenu(id);
		bind(request,menu);
		//menuService.update(menu);
		this.menuService.saveMenu(menu);
		model.addAttribute("menu", menu);
		model.addAttribute("done", 1);
		return "/sys/menu/editMenu";
	}
	
	
	/** 删除 */
	//@RequestMapping(value="/{id}",method=RequestMethod.DELETE)
	@Override
	public @ResponseBody String delete(@PathVariable Long id,Model model) {
		logger.info("delete..............");
		
		logger.info("注入这个进行批量删除dbUtilsTemplate=== "+dbUtilsTemplate);
		//logger.info("items=== "+items);
		return null;
	}

	/** 批量删除 */
	//@RequestMapping(method=RequestMethod.DELETE)
	//@RequestBody 可以传递----ok 这样就可以传递参数了。在进行多个参数测试
	//@RequestParam  不能进行传递
	//@RequestMapping(value="/batchDelete",method=RequestMethod.DELETE)  @RequestParam("items")
	@Override
	public @ResponseBody String batchDelete(@RequestBody String items,HttpServletRequest request,HttpServletResponse response) {
		logger.info("batchDelete..............");
		Map<String, String> map = new HashMap<String, String>();
		logger.info("注入这个进行批量删除dbUtilsTemplate=== "+dbUtilsTemplate);//如何使用这个组件批量删除
		logger.info("items.............."+items+"id====");
		//String ids = request.getParameter("items");
		String[] idsArray = items.split(",");
		try {
			for (String id : idsArray) {
				logger.info("开始删除"+id);
				menuService.deleteMenu(Long.parseLong(id));
			}
			map.put("success", "删除成功");
			logger.info("删除成功");
		} catch (Exception e) {
			logger.warn("异常处理:  "+e);
			map.put("error", "删除失败");
			logger.info("删除失败");
		}
		renderJson(response, map);
		logger.info("返回去吧。。。。。。。。。。");
//		Object[] params = new Object[items.length()];//items.length();
//		//params = {items};
//		for (int i = 0; i < params.length; i++) {
//			params[i] = itemsArray[i];
//		}
//		//params.
//		//Object[][] params = new Object[][] { {1694},{1693}};
//		//Object[][] idsArray = ids.split(",");
//		//delete from Menus where id in (1689,1690);
//		int result = 
//	    	dbUtilsTemplate.update("delete from MENUS where id in ( ? )",items);
//		logger.info("length:  "+result);
		/*for(int i = 0; i < items.length; i++) {
			//userInfoManager.removeById(items[i]);
			logger.info("id--- "+items[i]);
		}*/
		return null;
	}
	
	@RequestMapping(value="/doSave")
	public String doSave(HttpServletRequest request,HttpServletResponse response) {
		logger.info("doSave............");
		GridServerHandler gridServerHandler = new GridServerHandler(request,response);
		//取得新增的数据集合, 每条数据记录在 map 里
		//List insertedRecords = gridServerHandler.getInsertedRecords();
		JsonNode insertJsonNode = gridServerHandler.getInsertedJsonNodeRecords();
		Iterator<JsonNode> insertNodes = insertJsonNode.getElements(); 
		ObjectMapper mapper = new ObjectMapper(); 
		while (insertNodes.hasNext()) {  
			logger.info("保存操作.............");
			Menu entity = new Menu();
            JsonNode node = insertNodes.next();
            //String icon = node.get("icon").getTextValue();
            //entity.setIcon(icon);
            try {
            	entity = mapper.readValue(node, Menu.class);
				logger.info("menu-icon- "+entity.getIcon()+",name== "+entity.getMenuName());
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
            this.menuService.saveMenu(entity);
        }
		
		JsonNode updateJsonNode = gridServerHandler.getUpdatedJsonNodeRecords();
		Iterator<JsonNode> updateNodes = updateJsonNode.getElements(); 
		
		while (updateNodes.hasNext()) {  
			logger.info("更新操作.............");
			
			//ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally  
            JsonNode node = updateNodes.next();
            try {
				menu = mapper.readValue(node, Menu.class);
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
            
			this.menuService.saveMenu(menu);
        }
		
		JsonNode deleteJsonNode = gridServerHandler.getDeletedJsonNodeRecords();
		Iterator<JsonNode> deleteNodes = deleteJsonNode.getElements(); 
		
		while (deleteNodes.hasNext()) {  
			logger.info("删除操作.............");
            JsonNode node = deleteNodes.next();
            Long id = node.get("id").getLongValue();
            
            this.menuService.deleteMenu(id);
        }
		
		//设置该次操作是否成功.
		gridServerHandler.setSuccess(true);
		
		//如果操作不成功 你也可以自定义一些异常信息发送给客户端.
		//gridServerHandler.setSuccess(false);
		
		//向客户端输出json字符串.
		renderJson(response,gridServerHandler.getSaveResponseText());
		logger.info("SUCCESS............");
		return null;//new ModelAndView("/company/list");
	}
	
	@Override
	public String list(HttpServletRequest request,HttpServletResponse response,
			Menu menu,Model model){
		logger.info("***************list********************");
		Map map = new HashMap();
		GridServerHandler gridServerHandler = new GridServerHandler(request,response);
		Map param = gridServerHandler.getParameters() ;
		logger.info("传递参数param---- "+param);
		JsonNode parametersJsonNode = gridServerHandler.getParametersJsonNode();
		logger.info("传递参数param---- "+parametersJsonNode);
		//过滤
		List sortInfoList = gridServerHandler.getSortInfo();
		logger.info("sortInfoList---"+sortInfoList.size());
		List list = gridServerHandler.getFilterInfo();
		logger.info("list--- "+list);
		//获取总记录数
		int pageNo = gridServerHandler.getPageNum();//第几页
		//logger.info("pageNo------------ "+pageNo);
		int pageSize = gridServerHandler.getPageSize();//每页多少条记录
		//logger.info("pageSize------------ "+pageSize);
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page = this.menuService.getAllMenuByHql(map, pageNo, pageSize);
		logger.info("page size== "+page.getTotalCount());
		//jsonAwareCollect.add("advertisePosition");
		//page.setResult(result);
		gridServerHandler.setTotalRowNum(page.getTotalCount());
		gridServerHandler.setData(page.getResult());
		//绕过jsp 、freemarker 进行，非常的酷
		renderJson(response, gridServerHandler.getLoadResponseText());
		
		return null;
	}
	
	
	
	@RequestMapping(value="/tree")
	public String tree(HttpServletRequest request,HttpServletResponse response){
		logger.info("要实现梅花树tree.......");
		return "/sys/menu/tree";
	}
	
	@RequestMapping(value="/thickbox/{id}")
	public String thickbox(@PathVariable("id") String id){
		logger.info("thickbox-*************-- ");
		return "/sys/thickbox/test_"+id;
	}
	
	@RequestMapping(value="/dyTree/{parentId}")
	public String getTree(HttpServletRequest request,@PathVariable("parentId") String parentId){
		logger.info("开始构建树结构.....................");
		System.out.println("父id:  "+parentId);
		menuList = menuService.getAllMenuList();

		String nodes = "";
        nodes = "var data = {};" +
        		"data['-1_1']='text:菜单管理_1;';";

        for (Menu menu : menuList) {
            nodes += "data[\'" + menu.getParentId().toString() + "_" 
            		+ menu.getId().toString() + "\'] = \'text:" 
            		+ menu.getMenuName()+"_"+menu.getId().toString() + ";\';\r\n";
        }
        nodes += "Using(\"System.Web.UI.WebControls.MzTreeView\");";
        nodes += "var tree = new MzTreeView();";
        nodes += "tree.dataSource = data;";
        //nodes += "tree.setJsDataPath(\"MzTreeView10/csdn/community/treedata/\");";
        //nodes += "tree.setXmlDataPath(\"MzTreeView10/csdn/community/treedata/\");";
        //a.rootId="1"; 
        nodes += "tree.autoSort=false;";
        nodes += "tree.useCheckbox=false;"; //false
        nodes += "tree.canOperate = true;";
        nodes += "document.write(tree.render());";
        nodes += "tree.expandLevel(2);";
        //展开所有节点
        //nodes += "tree.expandAll(1);";
        //return nodes; 
        if ("1".equals(parentId)) {
			parentId = "1_"+parentId;
		}else{
			logger.info("parentId: "+parentId);
			Menu menu = this.menuService.getMenu(Long.parseLong(parentId));
			String menuId = menu.getParentId();//父节点，最终是聚焦点
			parentId = menuId+"_"+parentId;
		}
		logger.info("tree:  "+nodes);
		
		request.setAttribute("treeData", nodes);
		
		request.setAttribute("parentId", parentId);
		
		return "/sys/menu/dy_tree";
	}
	
	@RequestMapping(value="/staticTree")
	public String getStaticTree(HttpServletRequest request,Model model, ModelMap modelMap){
		logger.info("构造的静态树");
		String nodes = "";
		nodes += "var data={};";
        nodes += "data[\"-1_1\"] = \"text: CSDN社区起始点;\";";
        
        nodes += "data['1_9001'] = 'text: 我感兴趣的社区;';";
        nodes += "data['1_9002'] = 'text: 我的技术社区 xml; XMLData: /static/js/ui/scripts/Csdn/community/treedata/mycommunity.xml';";
        nodes += "data['1_9009'] = 'text: 开发语言; url:/Expert/ForumsList.asp?typenum=1&roomid=1 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/language.js';";
        nodes += "data['1_54'] = 'text: Java 技术; url:/Expert/ForumsList.asp?typenum=1&roomid=54 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/java.js';";
        nodes += "data['1_52'] = 'text: .Net 技术; url:/Expert/ForumsList.asp?typenum=1&roomid=52 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/donnet.js';";
        nodes += "data['1_9003'] = 'text: IBM developerWorks 技术社区; JSData: /static/js/ui/scripts/Csdn/community/treedata/ibm.js';";
        nodes += "data['1_9004'] = 'text:Borland 技术社区; JSData: /static/js/ui/scripts/Csdn/community/treedata/borland.js';";
        nodes += "data['1_2'] = 'text: 数据库开发; url:/Expert/ForumsList.asp?typenum=1&roomid=2 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/db.js';";
        nodes += "data['1_3'] = 'text: WEB 开发; url:/Expert/ForumsList.asp?typenum=1&roomid=3 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/web.js';";
        nodes += "data['1_4'] = 'text: 软件工程/管理; url:/Expert/ForumsList.asp?typenum=1&roomid=4 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/project.js';";
        nodes += "data['1_5'] = 'text: 企业开发; url:/Expert/ForumsList.asp?typenum=1&roomid=5 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/enterprise.js';";
        nodes += "data['1_6'] = 'text: 专题开发/技术/项目; url:/Expert/ForumsList.asp?typenum=1&roomid=6 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/special.js';";
        nodes += "data['1_7'] = 'text: 多媒体/设计/Flash开发; url:/Expert/ForumsList.asp?typenum=1&roomid=7 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/multimedia.js';";
        nodes += "data['1_8'] = 'text: Linux/Unix 社区; url:/Expert/ForumsList.asp?typenum=1&roomid=8 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/linux.js';";
        nodes += "data['1_9'] = 'text: 硬件/嵌入开发; url:/Expert/ForumsList.asp?typenum=1&roomid=9 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/embed.js';";
        nodes += "data['1_63'] = 'text: 移动平台; url:/Expert/ForumsList.asp?typenum=1&roomid=63 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/moble.js';";
        nodes += "data['1_609'] = 'text: 英特尔多核计算技术; data:roomid=609';";
        nodes += "data['1_10'] = 'text: Windows 专区; url:/Expert/ForumsList.asp?typenum=1&roomid=10 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/window.js';";
        nodes += "data['1_9005'] = 'text: Microsoft Office 应用与开发; JSData: /static/js/ui/scripts/Csdn/community/treedata/office.js';";
        nodes += "data['1_11'] = 'text: 硬件使用; url:/Expert/ForumsList.asp?typenum=1&roomid=11 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/hardware.js';";
        nodes += "data['1_20'] = 'text: 计算机图书; JSData: /static/js/ui/scripts/Csdn/community/treedata/book.js';";
        nodes += "data['1_13'] = 'text: 软件培训/认证/考试; url:/Expert/ForumsList.asp?typenum=1&roomid=13 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/train.js';";
        nodes += "data['1_14'] = 'text: 扩充话题; url:/Expert/ForumsList.asp?typenum=1&roomid=14 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/expansion.js';";
        nodes += "data['1_9006'] = 'text: 程序员杂志社; JSData: /static/js/ui/scripts/Csdn/community/treedata/mag.js';";
        nodes += "data['1_15'] = 'text: 社区支持; url:/Expert/ForumsList.asp?typenum=1&roomid=15';";
        nodes += "data['15_1501'] = 'text: 公告; data:roomid=1501';";
        nodes += "data['15_1502'] = 'text: 新版申请; data:roomid=1502';";
        nodes += "data['15_1503'] = 'text: 建议和意见; data:roomid=1503';";
        nodes += "data['15_1504'] = 'text: 投诉专区; data:roomid=1504';";
        nodes += "data['15_1505'] = 'text: 社区电子杂志; data:roomid=1505';";
        nodes += "data['15_1500001'] = 'text: CSDN Blog支持专区; data:roomid=1506';";
        nodes += "data['1_16'] = 'text: 产品/厂家; url:/Expert/ForumsList.asp?typenum=1&roomid=16 ; JSData: /static/js/ui/scripts/Csdn/community/treedata/manufacturer.js';";
        nodes += "data['1_9007'] = 'text: 系统功能; JSData: /static/js/ui/scripts/Csdn/community/treedata/system.js';";
        nodes += "data['1_9008'] = 'text: 版主管理; url:/Expert/Manage/index1.asp ; JSData: /static/js/ui/scripts/Csdn/community/treedata/manage.js';";



        //*
        nodes += "Using(\"System.Web.UI.WebControls.MzTreeView\");";
        nodes += "var a = new MzTreeView();";
        nodes += "a.dataSource = data;";
        //a.loadXmlDataString(xmlstr, 1);

        //a.setJsDataPath("/ui//static/js/ui/scripts/Csdn/community/treedata/");
        //a.setXmlDataPath("/ui//static/js/ui/scripts/Csdn/community/treedata/");
        //a.rootId="1";
        nodes += "a.autoSort=false;";
        nodes += "a.useCheckbox=true;";
        nodes += "a.canOperate=true;";
        nodes += "document.write(a.render());";
        nodes += "a.expandLevel(1);";
        model.addAttribute("nodes", nodes);
        request.setAttribute("nodes", nodes);
        modelMap.addAttribute("nodes", nodes);
        return "/sys/menu/staticTree";
	}
	
	
	
	@RequestMapping(value="/admin")
	public String admin(){
		//logger.info("实现新的系统后台");
		return "/sys/admin";
	}
	
	@RequestMapping(value="/main")
	public String main(){
		logger.info("222222222222系统主要后台");
		return "/sys/admin_app";
	}
	
}
